var elemOperation = document.getElementById('operation');
var elemTbody = document.getElementById('tbody');
var elemClear = document.getElementById('clear');
var elemEsql = document.getElementById('esql');


var viewStr = "";//设置显示字符缓存
var queueRunNum = [];//参与运算数字队列
var queueRunSym = [];//参与运算运算符队列

//利用事件代理绑定事件
elemTbody.onclick=function(event){
	var event = event ? event : window.event;
	var target = event.target || event.srcElement;

	var className = target.className;//当前事件源的类名
	var thisValue = target.getAttribute('data-value');//当前事件源的value
	// console.log(thisValue);
	var currentNum = parseFloat(elemOperation.value);//当前显示框里的数字
	// console.log(target);
	// console.log(event);
	if(target && target.nodeName == "TD" && className != "no-write"){
		if(className == "symbol"){
			//累加运算
			queueRunNum.push(currentNum);
			queueRunSym.push(thisValue);
			viewStr = "";
		}else{
			//输入数字
			var targetValue = thisValue;
			viewStr = viewStr + targetValue;
			elemOperation.value = viewStr; 
		}
	}else{
		var currentId = target.id,superResult;
		switch(currentId){
			//平方
			case "square" :
				superResult = Math.pow(currentNum,2);
				break;
			//开平方
			case "squareRoot" :
				superResult = Math.sqrt(currentNum);
				break;
			//正弦
			case "sin" :
				superResult = parseFloat(Math.sin(currentNum*Math.PI/180).toFixed(2));
				break;
			//余弦
			case "cos" :
				superResult = parseFloat(Math.cos(currentNum*Math.PI/180).toFixed(2));
				break;
			//正切
			case "tan" :
				superResult = parseFloat(Math.tan(currentNum*Math.PI/180).toFixed(2));
				break;
			//清除
			case "clear" :
				clear(currentNum);
				return;
			//等于
			case "esql" :
				esql(currentNum);
				return;
			//归零
			case "ac":
				ac();
				return;
			default:
				return;
		}
		elemOperation.value = superResult;
		viewStr = "";
	}
}

function clear(currentNum){
	var currentStr = currentNum.toString();
	if(currentStr == 'NaN'){
		var newStr = "";
	}else{
		var newStr = currentStr.slice(0,-1);
	}
	viewStr = newStr;
	elemOperation.value = newStr;
}

function esql(currentNum) {
	var result,expression = "";
	queueRunNum.push(currentNum);//将等于之前的数字塞入数字队列
	//将运算队列拼成字符串
	for(var i = 0; i < queueRunNum.length; i++){
		queueRunSym[i] = i == (queueRunNum.length-1) ? "" : queueRunSym[i];
		expression = expression + queueRunNum[i] + queueRunSym[i];
	}
	//运行字符串js，使用CalcEval插件解决javascript浮点数误差
	// var ce = new CalcEval();
	// result = ce.eval("("+expression+")");
	//判断除数是否为0
	if(result == Infinity){
		alert("出错，除数不能为零")
	}
	
	elemOperation.value = result;
	//清空队列
	queueRunNum = [];
	queueRunSym = [];
	viewStr = "";
}
function ac(){
	elemOperation.value = "0";
	viewStr = "";
}